package com.emip.view;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.web.servlet.view.document.AbstractExcelView;
import org.springframework.stereotype.Component;

import com.emip.pojo.Data;
import com.emip.pojo.Report;
import com.emip.util.Util;

@Component
public class ReportExcelView extends AbstractExcelView {

	
	@Override
	protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook,
		HttpServletRequest request, HttpServletResponse response)
		throws Exception {
 
		Report report = (Report) model.get("report");
		if (report == null) return;
		List<Map<String, Object>> bodys = report.getBodys();
		List<Map<String, Object>> footers = report.getFooters();
		
		
		List<String> headerNames = report.getColNames();
		List<String> indexes = report.getIndexes();
		
		Map<String, Integer> position = new HashMap<String, Integer>();
//		String title = (String) model.get("title");
		
		//create a wordsheet
		HSSFSheet sheet = workbook.createSheet("Report");
		HSSFCellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); //填充单元格
		cellStyle.setFillForegroundColor(HSSFColor.DARK_RED.index); //填暗红色
		
		//set header names
		HSSFRow header = sheet.createRow(0);
		for (int i = 0; i < headerNames.size(); i++) {
			header.createCell(i+1).setCellValue(headerNames.get(i));
			position.put(indexes.get(i), i+1);
		}
		position.put("time", 0);
 
		int rowNum = 1;
		for (int i = 0; i < bodys.size(); i++) {
			Map<String, Object> dataRow = bodys.get(i);
			HSSFRow row = sheet.createRow(rowNum++);
			for (Map.Entry<String, Object> entry : dataRow.entrySet()) {
				//创建新的单元格
				HSSFCell cell = row.createCell(position.get(entry.getKey()));
				Object obj = entry.getValue();
				if (obj instanceof Data) {
					Data data = (Data) entry.getValue();
					cell.setCellValue(Util.Float2String(data.getValue()));
					if (data.getFlag() != null) 
						cell.setCellStyle(cellStyle);
				} else {
					cell.setCellValue(obj.toString());
				}
			}
		}
		
		for (int i = 0; i < footers.size(); i++) {
			Map<String, Object> dataRow = footers.get(i);
			HSSFRow row = sheet.createRow(rowNum++);
			for (Map.Entry<String, Object> entry : dataRow.entrySet()) {
				HSSFCell cell = row.createCell(position.get(entry.getKey()));
				cell.setCellValue(entry.getValue().toString());
			}
		}
	}
	
}
